import React, {ChangeEvent, FC, useState} from 'react';
import {Input, Empty} from "antd";
import {searchBooks} from "@/apis/book";
import {ApiConstants} from "@/apis/constants";
import {errorMessage} from "@/common/components/Message";
import {BookConfig} from "@/apis/recommend";
import "./search.scss"
import {navigation} from "@/common/components/Navigation";

let timer: NodeJS.Timeout
let abortController: AbortController | null

const {Search} = Input

export const SearchBooks: FC = () => {
    const [resultList, setResultList] = useState<BookConfig[] | null>(null)
    const [isFocus, setIsFocus] = useState<boolean>(false)
    const search = async (event: ChangeEvent<HTMLInputElement>) => {
        abortController?.abort()
        const {value} = event.target
        if (!value.trim()) return null
        abortController = new AbortController()
        const {code, data, msg} = await searchBooks(abortController, value, 10)
        if (code !== ApiConstants.SUCCESS) return errorMessage(msg)
        setResultList(data)
        abortController = null
    }

    const focusHandler = () => {
        setIsFocus(true)
    }
    const blurHandler = () => {
        timer = setTimeout(() => {
            setIsFocus(false)
            setResultList(null)
        },100)
    }

    const locationInfo = (id: string) => {
        clearTimeout(timer)
        setResultList(null)
        setIsFocus(false)
        navigation(`/bookInfo?bookId=${id}`)
    }

    return (
        <div className="search">
            <Search className="search_input"
                    placeholder="请输入图书名称"
                    onChange={search}
                    onFocus={focusHandler}
                    onBlur={blurHandler}
                    allowClear/>
            <div className="search_result" style={{display: isFocus && resultList ? "block" : "none"}}>
                {
                    resultList?.length ?
                        resultList.map(
                            book => <div className="search_result_item" key={book.id} onClick={() => {
                                locationInfo(book.id)
                            }}>{book.name}</div>
                        )
                        : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}/>
                }
            </div>
        </div>
    );
}
